package com.nine.mymall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nine.common.constant.ProductConstant;
import com.nine.common.to.SkuReductionTo;
import com.nine.common.to.SpuBoundTo;
import com.nine.common.to.es.SkuEsModel;
import com.nine.common.utils.PageUtils;
import com.nine.common.utils.Query;
import com.nine.common.utils.R;
import com.nine.common.vo.SkuHasStockVo;
import com.nine.mymall.product.dao.SpuInfoDao;
import com.nine.mymall.product.entity.*;
import com.nine.mymall.product.fegin.CouponFeginService;
import com.nine.mymall.product.fegin.SearchFeginService;
import com.nine.mymall.product.fegin.WareFeginService;
import com.nine.mymall.product.service.*;
import com.nine.mymall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    /**
     * 品牌
     */
    @Autowired
    BrandService brandService;

    /**
     * 分类
     */
    @Autowired
    CategoryService categoryService;

    // 远程 fegin 调用接口
    @Autowired
    CouponFeginService couponFeginService;

    @Autowired
    WareFeginService wareFeginService;

    /**
     * 检索服务
     */
    @Autowired
    SearchFeginService searchFeginService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        // 1、保存 spu 基本信息（pms_spu_info）
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2、保存 spu 的描述图片（pms_spu_info_desc）
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        descService.saveSpuInfoDesc(descEntity);

        // 3、保存 spu 图片集（pms_spu_images）
        List<String> images = vo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(), images);

        // 4、保存 spu 的规格参数（pms_product_attr_value）
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            attrValueEntity.setAttrName(attrEntity.getAttrName());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        // 直接调用 saveBatch 方法保存数据
        productAttrValueService.saveBatch(attrValueEntities);

        // 5、保存spu的积分信息（需要跨数据库，mymall-sms -> sms_spu_bounds）
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeginService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败！");
        }


        // 6、保存当前 spu 对应的所有 sku 信息
        // 6.1、sku 的基本信息（pms_sku_info）
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 额外设置的值
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());


                List<Images> skuImages = item.getImages();
                String defaultImg = "";
                for (Images img : skuImages) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                        break;
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                // 6.2、sku 图片信息（pms_sku_images）
                List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回true需要，返回false，不需要
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());

                // TODO 没有图片，路径无需保存
                skuImagesService.saveBatch(skuImagesEntities);


                // 6.3、sku 销售属性信息（pms_sku_sale_attr_value）
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


                // 6.4、sku 的优惠、满减等信息（需要跨数据库，mymall-sms -> sms_sku_ladder | sms_sku_full_reduction | sms_member_price）

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                // skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) 比较
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R rSku = couponFeginService.saveSkuReduction(skuReductionTo);
                    if (rSku.getCode() != 0) {
                        log.error("远程保存spu优惠信息失败！");
                    }
                }

            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * 分页查询商品 spu 信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {

        /**
         *  key: '华为',//检索关键字
         *    catelogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         */
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);


    }

    @Override
    public void up(Long spuId) {

        List<ProductAttrValueEntity> attrs = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = attrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());

        // TODO 这边的逻辑有点奇怪，。。。。

        // 检索的属性
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrList = new ArrayList<>();
        List<SkuEsModel.Attrs> attrsList = attrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs esAttrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, esAttrs);
            return esAttrs;
        }).collect(Collectors.toList());

        // 1、查出当前 spuid 对应的所有 sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        if (skus == null || skus.size() == 0) {
            log.error("通过spu_id:" + spuId + ",未获取到sku相关信息");
            return;
        }

        // 查询所有的skuid的集合
        //List<Long> skuIds = skus.stream().map(sku -> sku.getSkuId()).collect(Collectors.toList());
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            // 远程调用库存系统，库存系统查询是否有库存
            R hasStock = wareFeginService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> data = hasStock.getData(typeReference);
            stockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存调用出现异常，原因：{}", e);
        }

        // 2、封装每个sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            // 组装要上架的数据
            SkuEsModel esModel = new SkuEsModel();

            BeanUtils.copyProperties(sku, esModel);
            // 额外处理的字段
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // hasStock
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // hotScore，热度评分，一开始都是 0
            esModel.setHotScore(0L);

            // 品牌
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            // 分类
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            // sku 所有的规格属性 （可以被检索的）
            esModel.setAttrs(attrsList);


            return esModel;
        }).collect(Collectors.toList());

        // 将数据发送给 es 进行调用
        R statusUp = searchFeginService.productStatusUp(upProducts);
        if (statusUp.getCode() == 0) {
            // 成功
            // 修改spu上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 失败

            // TODO 重复调用，接口幂等性 重试机制
        }

    }

}